<template>
  <div class="health-history-container">
    <h2 class="health-history-title">健康数据历史</h2>
    
    <div class="filter-section">
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="健康类型">
            <el-select v-model="filterForm.typeId" clearable placeholder="全部类型" @change="handleFilterChange">
              <el-option
                v-for="type in healthTypes"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilterChange"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleFilterChange">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <div class="data-section">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
        <el-tab-pane label="列表视图" name="list">
          <el-table
            :data="records"
            border
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="recordDate" label="日期" width="120" />
            <el-table-column prop="recordTime" label="时间" width="120" />
            <el-table-column prop="typeName" label="类型" width="150" />
            <el-table-column label="数值" min-width="150">
              <template #default="scope">
                <span>{{ scope.row.recordValue }} {{ scope.row.unit }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isAbnormal ? 'danger' : 'success'">
                  {{ scope.row.isAbnormal ? '异常' : '正常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container" v-if="pagination.total > 0">
            <el-pagination
              background
              layout="prev, pager, next, total"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              :current-page="pagination.currentPage"
              @current-change="handlePageChange"
            />
          </div>
          
          <el-empty description="暂无数据" v-if="records.length === 0 && !loading" />
        </el-tab-pane>
        
        <el-tab-pane label="图表视图" name="chart">
          <div class="chart-container" v-loading="chartLoading">
            <div v-if="!selectedTypeId">
              <el-empty description="请选择健康类型以查看趋势图">
                <template #description>
                  <div>
                    <p>请在上方筛选栏选择一种健康类型以查看趋势图</p>
                  </div>
                </template>
              </el-empty>
            </div>
            <div v-else-if="chartData.length === 0 && !chartLoading">
              <el-empty description="暂无数据">
                <template #description>
                  <div>
                    <p>当前选择的健康类型和日期范围内暂无数据</p>
                  </div>
                </template>
              </el-empty>
            </div>
            <div v-else-if="chartData.length > 0" class="chart-wrapper" id="healthChart"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="statistics-section" v-if="showStatistics && statistics.length > 0">
      <h3 class="section-title">数据统计</h3>
      <el-row :gutter="20">
        <el-col :span="8" v-for="item in statistics" :key="item.typeId">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-title">{{ item.typeName }}</div>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="记录次数">{{ item.count }}</el-descriptions-item>
              <el-descriptions-item label="平均值" v-if="item.avg">{{ item.avg }} {{ item.unit }}</el-descriptions-item>
              <el-descriptions-item label="最小值" v-if="item.min">{{ item.min }} {{ item.unit }}</el-descriptions-item>
              <el-descriptions-item label="最大值" v-if="item.max">{{ item.max }} {{ item.unit }}</el-descriptions-item>
              <el-descriptions-item label="异常次数">{{ item.abnormalCount }} ({{ item.abnormalRate }}%)</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 获取当前用户ID
let userId = null
const userInfoStr = localStorage.getItem('userInfo')
const userStr = localStorage.getItem('user')

if (userInfoStr) {
  try {
    userId = JSON.parse(userInfoStr).id
    console.log('从userInfo获取到用户ID:', userId)
  } catch (e) {
    console.error('解析userInfo失败:', e)
  }
} else if (userStr) {
  try {
    userId = JSON.parse(userStr).id
    console.log('从user获取到用户ID:', userId)
  } catch (e) {
    console.error('解析user失败:', e)
  }
}

if (!userId) {
  // 如果都没有获取到，默认使用ID为8用于测试
  userId = 8
  console.log('未找到用户信息，使用默认ID:', userId)
}

// 健康类型列表
const healthTypes = ref([])
const loading = ref(false)
const chartLoading = ref(false)
const activeTab = ref('list')
const showStatistics = ref(true)

// 图表实例
let chart = null

// 筛选表单
const filterForm = reactive({
  typeId: '',
  startDate: '',
  endDate: ''
})

// 选中的类型ID
const selectedTypeId = computed(() => filterForm.typeId)

// 日期范围
const dateRange = ref([])

// 初始化日期范围为最近30天
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  
  filterForm.startDate = formatDate(start)
  filterForm.endDate = formatDate(end)
  dateRange.value = [filterForm.startDate, filterForm.endDate]
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 健康记录列表
const records = ref([])

// 图表数据
const chartData = ref([])

// 统计数据
const statistics = ref([])

// 健康类型映射
const healthTypeMap = ref({})

// 获取健康类型
const getHealthTypes = async () => {
  try {
    // 尝试从本地存储获取数据
    const localData = localStorage.getItem('health_types')
    if (localData) {
      healthTypes.value = JSON.parse(localData)
      healthTypeMap.value = healthTypes.value.reduce((map, type) => {
        map[type.id] = type
        return map
      }, {})
      console.log('从本地存储加载健康类型:', healthTypes.value)
      return
    }
    
    // 使用模拟数据
    loadDemoTypes()
    
    // 转换为map便于查找
    healthTypeMap.value = healthTypes.value.reduce((map, type) => {
      map[type.id] = type
      return map
    }, {})
    
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  } catch (error) {
    console.error('获取健康记录类型失败', error)
    // 加载演示数据
    loadDemoTypes()
    
    // 转换为map便于查找
    healthTypeMap.value = healthTypes.value.reduce((map, type) => {
      map[type.id] = type
      return map
    }, {})
    
    // 保存演示数据到本地存储
    localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
  }
}

// 加载演示的健康类型数据
const loadDemoTypes = () => {
  healthTypes.value = [
    { id: 1, name: '血压(收缩压)', unit: 'mmHg', isNumeric: true, minValue: 60, maxValue: 180, icon: 'iconfont icon-blood-pressure' },
    { id: 2, name: '血压(舒张压)', unit: 'mmHg', isNumeric: true, minValue: 40, maxValue: 120, icon: 'iconfont icon-blood-pressure' },
    { id: 3, name: '心率', unit: '次/分钟', isNumeric: true, minValue: 40, maxValue: 200, icon: 'iconfont icon-heart-rate' },
    { id: 4, name: '血糖(空腹)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 6.1, icon: 'iconfont icon-blood-glucose' },
    { id: 5, name: '血糖(餐后2小时)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 7.8, icon: 'iconfont icon-blood-glucose' },
    { id: 6, name: '体重', unit: 'kg', isNumeric: true, minValue: 30, maxValue: 150, icon: 'iconfont icon-weight' },
    { id: 7, name: '体温', unit: '℃', isNumeric: true, minValue: 35, maxValue: 42, icon: 'iconfont icon-temperature' },
    { id: 8, name: '睡眠时间', unit: '小时', isNumeric: true, minValue: 0, maxValue: 24, icon: 'iconfont icon-sleep' },
    { id: 9, name: '用药记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-medication' },
    { id: 10, name: '饮食记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-diet' }
  ]
}

// 英文健康类型名称翻译为中文
const translateTypeName = (engName) => {
  const typeMap = {
    'Blood Pressure (Systolic)': '血压(收缩压)',
    'Blood Pressure (Diastolic)': '血压(舒张压)',
    'Heart Rate': '心率',
    'Blood Glucose (Fasting)': '血糖(空腹)',
    'Blood Glucose (2h Postprandial)': '血糖(餐后2小时)',
    'Weight': '体重',
    'Body Temperature': '体温',
    'Sleep Duration': '睡眠时间',
    'Medication Record': '用药记录',
    'Dietary Record': '饮食记录'
  }
  return typeMap[engName] || engName
}

// 英文健康类型描述翻译为中文
const translateTypeDescription = (engDesc) => {
  const descMap = {
    'Systolic blood pressure measurement': '收缩压测量',
    'Diastolic blood pressure measurement': '舒张压测量',
    'Heart rate measurement': '心率测量',
    'Fasting blood glucose level': '空腹血糖水平',
    'Blood glucose 2 hours after meal': '餐后2小时血糖水平',
    'Body weight measurement': '体重测量',
    'Body temperature measurement': '体温测量',
    'Hours of sleep per night': '每晚睡眠时间',
    'Daily medication intake records': '每日药物摄入记录',
    'Daily food intake records': '每日食物摄入记录'
  }
  return descMap[engDesc] || engDesc
}

// 获取健康记录
const getRecords = async () => {
  if (!userId) return
  
  loading.value = true
  try {
    // 从本地存储获取健康记录
    let healthRecords = []
    const localData = localStorage.getItem(`health_records_${userId}`)
    if (localData) {
      healthRecords = JSON.parse(localData)
    }
    
    // 应用筛选
    if (filterForm.typeId) {
      healthRecords = healthRecords.filter(record => record.typeId === filterForm.typeId)
    }
    
    if (filterForm.startDate && filterForm.endDate) {
      healthRecords = healthRecords.filter(record => {
        const recordDate = record.recordDate
        return recordDate >= filterForm.startDate && recordDate <= filterForm.endDate
      })
    }
    
    // 排序
    healthRecords.sort((a, b) => {
      const dateA = new Date(`${a.recordDate} ${a.recordTime}`)
      const dateB = new Date(`${b.recordDate} ${b.recordTime}`)
      return dateB - dateA
    })
    
    // 应用分页
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    records.value = healthRecords.slice(start, end)
    pagination.total = healthRecords.length
    
    // 分析趋势并准备图表数据
    if (healthRecords.length > 0) {
      prepareTrendData(healthRecords)
    }
  } catch (error) {
    console.error('获取健康记录失败', error)
    records.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 准备趋势图表数据
const prepareTrendData = (healthRecords) => {
  const selectedTypeId = filterForm.typeId
  
  // 如果没有选择特定类型或者选择了非数值类型，则不显示趋势图
  if (!selectedTypeId) {
    showChart.value = false
    return
  }
  
  const selectedType = healthTypeMap.value[selectedTypeId]
  if (!selectedType || !selectedType.isNumeric) {
    showChart.value = false
    return
  }
  
  // 筛选当前类型的记录并按日期排序
  const typeRecords = healthRecords
    .filter(record => record.typeId === selectedTypeId)
    .sort((a, b) => {
      const dateA = new Date(`${a.recordDate} ${a.recordTime}`)
      const dateB = new Date(`${b.recordDate} ${b.recordTime}`)
      return dateA - dateB
    })
  
  if (typeRecords.length < 2) {
    showChart.value = false
    return
  }
  
  // 准备图表数据
  chartData.value = {
    labels: typeRecords.map(record => `${record.recordDate} ${record.recordTime.substring(0, 5)}`),
    datasets: [
      {
        label: selectedType.name,
        data: typeRecords.map(record => parseFloat(record.recordValue)),
        borderColor: '#409EFF',
        backgroundColor: 'rgba(64, 158, 255, 0.1)',
        borderWidth: 2,
        tension: 0.2,
        fill: true
      }
    ]
  }
  
  // 设置图表选项
  chartOptions.value = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      y: {
        beginAtZero: false,
        title: {
          display: true,
          text: selectedType.unit || ''
        }
      },
      x: {
        ticks: {
          maxRotation: 45,
          minRotation: 45
        }
      }
    },
    plugins: {
      title: {
        display: true,
        text: `${selectedType.name}变化趋势`,
        font: {
          size: 16
        }
      },
      legend: {
        display: false
      },
      tooltip: {
        enabled: true
      }
    }
  }
  
  // 如果有异常值，标记出来
  if (selectedType.minValue !== null && selectedType.maxValue !== null) {
    const abnormalIndices = typeRecords.map((record, index) => {
      const value = parseFloat(record.recordValue)
      return (value < selectedType.minValue || value > selectedType.maxValue) ? index : -1
    }).filter(index => index !== -1)
    
    if (abnormalIndices.length > 0) {
      chartData.value.datasets.push({
        label: '异常值',
        data: typeRecords.map((record, index) => {
          return abnormalIndices.includes(index) ? parseFloat(record.recordValue) : null
        }),
        borderColor: '#F56C6C',
        backgroundColor: 'rgba(245, 108, 108, 0.2)',
        borderWidth: 2,
        pointRadius: 6,
        pointHoverRadius: 8
      })
    }
  }
  
  showChart.value = true
}

// 获取统计数据
const getStatistics = async () => {
  if (!userId) return
  
  try {
    const params = {
      startDate: filterForm.startDate,
      endDate: filterForm.endDate
    }
    
    const res = await axios.get(`/api/health/statistics/${userId}`, { params })
    if (res.data.code === 200) {
      // 转换英文类型名称为中文
      statistics.value = res.data.result.statistics.map(item => {
        const type = healthTypes.value.find(t => t.id === item.typeId) || {}
        return {
          ...item,
          typeName: type.name || translateTypeName(item.typeName),
          unit: type.unit || '',
          abnormalRate: item.count > 0 ? ((item.abnormalCount / item.count) * 100).toFixed(1) : '0'
        }
      })
    } else {
      // 接口失败，使用模拟数据
      generateMockStatistics()
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
    // 接口异常，使用模拟数据
    generateMockStatistics()
  }
}

// 生成模拟统计数据
const generateMockStatistics = () => {
  statistics.value = [
    {
      typeId: 1,
      typeName: '血压(收缩压)',
      count: 15,
      min: '110',
      max: '140',
      avg: '125.6',
      unit: 'mmHg',
      abnormalCount: 2,
      abnormalRate: '13.3'
    },
    {
      typeId: 2,
      typeName: '血压(舒张压)',
      count: 15,
      min: '70',
      max: '95',
      avg: '82.1',
      unit: 'mmHg',
      abnormalCount: 3,
      abnormalRate: '20.0'
    },
    {
      typeId: 3,
      typeName: '心率',
      count: 10,
      min: '65',
      max: '88',
      avg: '76.2',
      unit: '次/分钟',
      abnormalCount: 0,
      abnormalRate: '0.0'
    }
  ]
}

// 筛选条件变化
const handleFilterChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    filterForm.startDate = dateRange.value[0]
    filterForm.endDate = dateRange.value[1]
  }
  
  pagination.currentPage = 1
  getRecords()
  
  if (activeTab.value === 'chart' && filterForm.typeId) {
    getChartData()
  }
  
  getStatistics()
}

// 切换标签页
const handleTabChange = (tab) => {
  if (tab.props.name === 'chart' && filterForm.typeId) {
    getChartData()
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.typeId = ''
  initDateRange()
  handleFilterChange()
}

// 处理页码变化
const handlePageChange = (page) => {
  pagination.currentPage = page
  getRecords()
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  if (chart) {
    chart.resize()
  }
})

// 监听类型变化，获取图表数据
watch(() => filterForm.typeId, (newVal) => {
  if (activeTab.value === 'chart' && newVal) {
    getChartData()
  }
})

// 组件挂载时初始化
onMounted(() => {
  initDateRange()
  getHealthTypes()
  getRecords()
  getStatistics()
})
</script>

<style scoped>
.health-history-container {
  padding: 20px;
}

.health-history-title {
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-card {
  padding: 10px;
}

.data-section {
  margin-bottom: 40px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.chart-container {
  height: 400px;
  margin-top: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
}

.section-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

.statistics-section {
  margin-top: 40px;
}

.statistic-card {
  margin-bottom: 20px;
}

.statistic-title {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 15px;
}

@media screen and (max-width: 768px) {
  .health-history-container {
    padding: 10px;
  }
  
  .filter-form {
    display: flex;
    flex-direction: column;
  }
  
  .el-form-item {
    margin-right: 0 !important;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .el-col {
    width: 100% !important;
  }
}
</style> 